package util

type BytecodeReader struct {
	Code []byte	// 存放字节码
	PC int	// 记录读取到了哪个字节
}

// 为避免每次都新建BytecodeReader而添加的方法
func (self *BytecodeReader)Reset(code []byte, pc int) {
	self.Code = code
	self.PC = pc
}

func (self *BytecodeReader)ReadUInt8() uint8 {
	i := self.Code[self.PC]
	self.PC++
	return i
}


func (self *BytecodeReader)ReadInt8() int8 {
	return int8(self.ReadUInt8())
}

func (self *BytecodeReader)ReadInt16() int16 {
	return int16(self.ReadUInt16())
}

func (self *BytecodeReader)ReadUInt16() uint16 {
	byte1 := uint16(self.ReadUInt8())
	byte2 := uint16(self.ReadUInt8())
	return (byte1 << 8) | byte2
}

func (self *BytecodeReader)ReadInt32() int32 {
	byte1 := int32(self.ReadUInt8())
	byte2 := int32(self.ReadUInt8())
	byte3 := int32(self.ReadUInt8())
	byte4 := int32(self.ReadUInt8())

	return (byte1 << 24 ) | (byte2 << 16) | (byte3 << 8) | byte4;
}

// used by lookupswitch and tableswitch
func (self *BytecodeReader) ReadInt32s(n int32) []int32 {
	ints := make([]int32, n)
	for i := range ints {
		ints[i] = self.ReadInt32()
	}
	return ints
}

// used by lookupswitch and tableswitch
func (self *BytecodeReader) SkipPadding() {
	for self.PC%4 != 0 {
		self.ReadUInt8()
	}
}